package promote.brozen.netty.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.concurrent.Executors;

/**
 * @author Brozen
 * @date 2020/9/27 4:03 PM
 * @email brozen@qq.com
 */
public class NettyEchoClient {

    public void start() throws InterruptedException {

        /*
            NioEventLoopGroup只设置线程数量无效，需要把线程池传递给第二个参数
            这个demo没有考虑拆包粘包
         */
        NioEventLoopGroup group = new NioEventLoopGroup(2, new DefaultThreadFactory("ClientWorker", true));

        try {
            Bootstrap client = new Bootstrap();
            client.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new NettyEchoChannelReader(false, "Client"))
                                    .addLast(new NettyEchoSINWriter());
                        }
                    });

            ChannelFuture f = client.connect("127.0.0.1", 8090).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        new NettyEchoClient().start();
    }

}
